<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>数据应用-数据项目</title>

    <link rel="stylesheet" href="../../plugins/fontawesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../../plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
    <link rel="stylesheet" href="../../plugins/icheck-bootstrap/icheck-bootstrap.min.css">
    <link rel="stylesheet" href="../../plugins/select2/css/select2.min.css">
    <link rel="stylesheet" href="../../plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css">
    <link rel="stylesheet" href="../../plugins/codemirror/codemirror.css">
    <link rel="stylesheet" href="../../plugins/codemirror/theme/darcula.css">
    <link rel="stylesheet" href="../../plugins/codemirror/addon/hint/show-hint.css">
    <link rel="stylesheet" href="../../adminLTE/css/adminlte.min.css">
    <link rel="stylesheet" href="../css/cloud.css">

    <style>
        .data-source-title {
            padding-bottom: 5px;
            border-bottom: 1px solid #ccc;
            display: block;
        }
    </style>
</head>
<body class="content-wrapper" style="padding: 15px">
<!--顶部条-->
<div style="padding: 0 7px 15px 7px" class="clearfix">
    <!--搜索输入框组-->
    <div class="input-group pull-left" style="width: 50%">
        <input id="keyword" class="form-control" type="search" placeholder="名称">
        <div class="input-group-append">
            <button id="search" class="btn btn-info btn-flat"><i class="fa fa-search"></i></button>
        </div>
    </div>
    <!--新增按钮-->
    <button id="add" class="btn btn-info pull-right"><i class="fa fa-plus"></i> 新建数据项目</button>
</div>
<!--数据展示-->
<div class="container-fluid">
    <table id="table" class="table table-sm table-hover table-bordered">
        <thead><tr>
            <th style="width: 4em">#</th>
            <th>名称</th>
            <th>数据源</th>
            <th style="width: 6em">状态</th>
            <th style="width: 11em">操作</th>
        </tr></thead>
        <tbody><tr>
            <td>{{index}}</td>
            <td>{{name}}</td>
            <td>{{dataSources}}</td>
            <td><span class="badge {{statusClass}}">{{status}}</span></td>
            <td>
                <button class="btn btn-xs btn-outline-primary modify" data-id="{{id}}">
                    <i class="fa fa-pencil"></i> 编辑
                </button>
                <button class="btn btn-xs btn-outline-danger remove" data-id="{{id}}">
                    <i class="fa fa-times"></i> 删除
                </button>
                <div class="btn-group">
                    <button type="button" class="btn btn-xs btn-outline-info dropdown-toggle dropdown-icon" data-toggle="dropdown">
                        <i class="fa fa-list-ul"></i> 更多
                    </button>
                    <div class="dropdown-menu dropdown-menu-outline-info dropdown-menu-right">
                        <a class="dropdown-item dropdown-item-xs more" data-id="{{id}}" href="javascript:void(0);"><i class="fa fa-commenting-o"></i> 详情</a>
                        <a class="dropdown-item dropdown-item-xs line" data-id="{{id}}" href="javascript:void(0);"><i class="fa fa-clock-o"></i> 时间线</a>
                        <a class="dropdown-item dropdown-item-xs init {{setInit}}" data-id="{{id}}"  href="javascript:void(0);"><i class="fa fa-file-code-o"></i> 初始化</a>
                        <a class="dropdown-item dropdown-item-xs upgrade {{setUpgrade}}" data-id="{{id}}"  href="javascript:void(0);"><i class="fa fa-arrow-up"></i> 升级</a>
                        <a class="dropdown-item dropdown-item-xs setEnable {{setEnable}}" data-id="{{id}}"  href="javascript:void(0);"><i class="fa fa-play-circle"></i> 启用</a>
                        <a class="dropdown-item dropdown-item-xs setDisable {{setDisable}}" data-id="{{id}}"  href="javascript:void(0);"><i class="fa fa-pause-circle"></i> 停用</a>
                    </div>
                </div>
            </td>
        </tr>
        </tbody>
    </table>
</div>
<!--加载更多-->
<div id="load-more" class="text-sm-center text-primary" style="display: none;">
    <span style="cursor: pointer"><i class="fa fa-hand-o-right"></i> 点击加载更多数据</span>
</div>
<!--正在加载-->
<div id="loading" class="text-sm-center text-gray" style="display: none;">
    <span><i class="fa fa-refresh fa-spin"></i> 正在加载...</span>
</div>
<!--全部加载-->
<div id="load-all" class="text-sm-center text-success" style="display: none;">
    <i class="fa fa-info-circle"></i> 已加载全部数据
</div>
<!--加载失败-->
<div id="load-error" class="text-sm-center text-danger" style="display: none;">
    <i class="fa fa-exclamation-triangle"></i> 加载失败
</div>
<!--详情-->
<div id="detail" class="side-panel right width400 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <input type="hidden" id="id" name="id">
        <div class="form-group">
            <label for="name" class="require">名称</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="请填写数据源名称" required>
        </div>
        <div class="form-group">
            <label for="dataSourceIds" class="require">数据源</label>
            <div class="select2-info">
                <select class="select2" data-dropdown-css-class="select2-info" data-placeholder="请选择数据源"
                        id="dataSourceIds" name="dataSourceIds" style="width: 100%;" multiple="multiple" required></select>
            </div>
        </div>
        <div class="bg-white">
            <button id="ok" class="btn btn-info"><i class="fa fa-check"></i> 确定</button>
            <button id="cancel" class="btn btn-default"><i class="fa fa-times"></i> 取消</button>
        </div>
    </div>
</div>
<!--更多-->
<div id="more-panel" class="side-panel right width1000 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <div class="container-fluid">
            <div id="more-panel-data-project-info">
                <div class="row" style="margin-bottom: 15px">
                    <div class="col-md-4">名称: {{name}}</div>
                    <div class="col-md-4">状态: <span class="badge {{statusClass}}">{{status}}</span></div>
                </div>
            </div>
            <div id="more-panel-data-source-list" class="row" style="margin-bottom: 15px">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            <label class="card-title">数据源列表</label>
                        </div>
                        <div class="card-body table-responsive p-0" style="max-height: 500px">
                            <table class="table table-sm table-hover table-head-fixed">
                                <thead><tr>
                                    <th>#</th>
                                    <th>名称</th>
                                    <th style="width: 5em">类型</th>
                                    <th>URL</th>
                                </tr></thead>
                                <tbody><tr>
                                    <td>{{index}}</td>
                                    <td>{{name}}</td>
                                    <td><span class="badge {{typeClass}}">{{type}}</span></td>
                                    <td>{{url}}</td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="bg-white">
            <button id="more-cancel" class="btn btn-default"><i class="fa fa-times"></i> 关闭</button>
        </div>
    </div>
</div>
<!--初始化-->
<div id="init-panel" class="side-panel right width400 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <div id="init-panel-body">
            <div class="form-group">
                <label class="data-source-title"><span class="badge {{typeClass}}" >{{typeValue}}</span> {{name}}</label>
                <div class="form-group">
                    <label for="init-panel-input-{{index}}" class="require">脚本文件</label>
                    <div class="input-group">
                        <input type="file" class="form-control" id="init-panel-input-{{index}}" data-id="{{id}}" data-index="{{index}}" placeholder="请选择脚本文件" required>
                    </div>
                    <div class="progress progress-xxs bg-white">
                        <div id="init-panel-progress-{{index}}" class="progress-bar bg-danger" style="width: 0%"></div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="init-panel-select-{{index}}" class="require">代理终端</label>
                    <div class="select2-info">
                        <select class="select2" data-dropdown-css-class="select2-info" data-placeholder="请选择代理终端"
                                id="init-panel-select-{{index}}" style="width: 100%;" required></select>
                    </div>
                </div>
            </div>
        </div>
        <div class="bg-white">
            <button id="init-ok" class="btn btn-info"><i class="fa fa-check"></i> 确定</button>
            <button id="init-cancel" class="btn btn-default"><i class="fa fa-times"></i> 关闭</button>
        </div>
    </div>
</div>
<!--升级-->
<div id="upgrade-panel" class="side-panel right width400 bg-white hide">
    <div class="bg-white" style="padding:20px">
        <div class="form-group">
            <label for="upgrade-panel-name" class="require">说明</label>
            <input type="text" class="form-control" id="upgrade-panel-name" placeholder="请填写说明" required>
        </div>
        <div id="upgrade-panel-body">
            <div class="form-group">
                <label class="require">脚本 <span class="badge {{typeClass}}" >{{typeValue}}</span> {{name}}</label>
                <div class="form-group">
                    <textarea id="upgrade-panel-input-{{index}}" name="sql" data-id="{{id}}"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label for="upgrade-panel-select-{{index}}" class="require">代理终端</label>
                <div class="select2-info">
                    <select class="select2" data-dropdown-css-class="select2-info" data-placeholder="请选择代理终端"
                            id="upgrade-panel-select-{{index}}" style="width: 100%;" required></select>
                </div>
            </div>
        </div>
        <div class="icheck-primary" style="margin-bottom: 15px !important;">
            <input id="upgrade-record-only" type="checkbox">
            <label for="upgrade-record-only">仅记录，不升级</label>
        </div>
        <div class="bg-white">
            <button id="upgrade-ok" class="btn btn-info"><i class="fa fa-check"></i> 确定</button>
            <button id="upgrade-cancel" class="btn btn-default"><i class="fa fa-times"></i> 关闭</button>
        </div>
    </div>
</div>

<script src="../../plugins/jquery/jquery.min.js"></script>
<script src="../../plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../../plugins/select2/js/select2.full.min.js"></script>
<script src="../../plugins/codemirror/codemirror.js"></script>
<script src="../../plugins/codemirror/mode/sql/sql.js"></script>
<script src="../../plugins/codemirror/addon/hint/show-hint.js"></script>
<script src="../../plugins/codemirror/addon/hint/sql-hint.js"></script>
<script src="../js/common.js"></script>
<script src="../js/child.js"></script>
<script>
    var select2DSCtrl = new Select2Ctrl("#dataSourceIds", Url.dataService.dataSourcePage, "id", "name", "select2");
    select2DSCtrl.init();

    var tableCtrl = new TableCtrl(
        Url.dataService.dataProjectSearchByKeyword,
        Url.dataService.dataProjectDetail,
        Url.dataService.dataProjectCreate,
        Url.dataService.dataProjectModify,
        Url.dataService.dataProjectRemove,
        function (template, record, index) {
            var statusClass = "bg-warning";
            var setInit = "";
            var setUpgrade = "";
            var setEnable = "";
            var setDisable = "";
            switch (record.status) {
                case "ENABLE": statusClass = "bg-success"; setInit = "disabled"; setUpgrade = ""; setEnable = "disabled"; setDisable = ""; break;
                case "DISABLE": statusClass = "bg-danger"; setInit = "disabled"; setUpgrade = "disabled"; setEnable = ""; setDisable = "disabled"; break;
                case "UNINITIALIZED": statusClass = "bg-danger"; setInit = ""; setUpgrade = "disabled"; setEnable = "disabled"; setDisable = "disabled";break;
                case "UPGRADING": statusClass = "bg-info"; setInit = "disabled"; setUpgrade = "disabled"; setEnable = "disabled"; setDisable = "disabled"; break;
                default: statusClass = "bg-warning";  setInit = "disabled"; setUpgrade = "disabled"; setEnable = "disabled"; setDisable = "disabled";break;
            }
            record.statusClass = statusClass;

            var dataSources = "";
            for (var i = 0; i < record.dataSources.length; i++) {
                var typeClass = record.dataSources[i].type === "MYSQL" ? "bg-info" : "bg-warning";
                dataSources += " <span class='badge "+ typeClass + "'>" + record.dataSources[i].name + "</span> ";
            }

            return template
                .replace(new RegExp("{{index}}", "gm"), index + 1)
                .replace(new RegExp("{{id}}", "gm"), record.id)
                .replace(new RegExp("{{name}}", "gm"), record.name)
                .replace(new RegExp("{{statusClass}}", "gm"), statusClass)
                .replace(new RegExp("{{status}}", "gm"), record.statusValue)
                .replace(new RegExp("{{dataSources}}", "gm"), dataSources)
                .replace(new RegExp("{{setInit}}", "gm"), setInit)
                .replace(new RegExp("{{setUpgrade}}", "gm"), setUpgrade)
                .replace(new RegExp("{{setEnable}}", "gm"), setEnable)
                .replace(new RegExp("{{setDisable}}", "gm"), setDisable)

        },
        function () {
            var record = {};
            record.id = $("#id").val();
            record.name = $("#name").val();
            record.dataSourceIds = $("#dataSourceIds").val();
            return record;
        }
    );
    tableCtrl.extraShowCreate = function() {
        select2DSCtrl.setEnable();
    };
    tableCtrl.extraShowModify = function(id) {
        var record = this.getById(id);
        if (record.status !== "UNINITIALIZED") {
            select2DSCtrl.setDisable();
        } else {
            select2DSCtrl.setEnable();
        }
    };
    tableCtrl.setEnable = function (id) {
        var self = this;
        var record = self.getById(id);
        $.ajax({
            url: Url.dataService.dataProjectEnable.replace("{id}", record.id),
            type: HttpMethod.patch,
            success: function (result, status, xhr) {
                tableCtrl.refreshById(id);
                parent.window.frameCtrl.toastr.success("启用成功！");
            }
        });
    };
    tableCtrl.setDisable = function (id) {
        var self = this;
        var record = self.getById(id);
        $.ajax({
            url: Url.dataService.dataProjectDisable.replace("{id}", record.id),
            type: HttpMethod.patch,
            success: function (result, status, xhr) {
                tableCtrl.refreshById(id);
                parent.window.frameCtrl.toastr.success("停用成功！");
            }
        });
    };
    tableCtrl.bindOtherEvent = function() {
        var self = this;
        $("#table").on("click", ".setEnable", function () {
            if ($(this).hasClass("disabled")) {
                return;
            }
            var id = $(this).attr("data-id");
            self.setEnable(id);
        });
        $("#table").on("click", ".setDisable", function () {
            if ($(this).hasClass("disabled")) {
                return;
            }
            var id = $(this).attr("data-id");
            self.setDisable(id);
        });
    };

    tableCtrl.moreDataProjectTemplate = "";
    tableCtrl.moreDataSourceTemplate = "";
    tableCtrl.getMoreTemplate = function () {
        this.moreDataProjectTemplate = $("#more-panel-data-project-info").html();
        this.moreDataSourceTemplate = $("#more-panel-data-source-list table tbody").html();
        $("#more-panel-data-project-info").html("");
        $("#more-panel-data-source-list table tbody").html("");
    };
    tableCtrl.showMore = function (id) {
        var record = this.getById(id);
        $("#more-panel-data-project-info").html("");
        $("#more-panel-data-source-list table tbody").html("");

        var html = this.moreDataProjectTemplate
            .replace(new RegExp("{{name}}", "gm"), record.name)
            .replace(new RegExp("{{statusClass}}", "gm"), record.statusClass)
            .replace(new RegExp("{{status}}", "gm"), record.statusValue);
        $("#more-panel-data-project-info").html(html);

        for (var i = 0; i < record.dataSources.length; i++) {
            var typeClass = "bg-info";
            if (record.dataSources[i].type === "DM") {
                typeClass = "bg-warning";
            }

            var html = this.moreDataSourceTemplate
                .replace(new RegExp("{{index}}", "gm"), (i + 1))
                .replace(new RegExp("{{name}}", "gm"), record.dataSources[i].name)
                .replace(new RegExp("{{typeClass}}", "gm"), typeClass)
                .replace(new RegExp("{{type}}", "gm"), record.dataSources[i].typeValue)
                .replace(new RegExp("{{url}}", "gm"), record.dataSources[i].url);
            $("#more-panel-data-source-list table tbody").append(html);
        }

        $("#more-panel").removeClass("hide");
    };
    tableCtrl.hideMore = function () {
        $("#more-panel").addClass("hide");
    };
    tableCtrl.bindMoreEvent = function () {
        var self = this;
        // 绑定更多按钮
        $("#table").on("click", ".more", function () {
            var id = $(this).attr("data-id");
            self.showMore(id);
        });
        $("#more-cancel").bind("click", function () {
            self.hideMore();
        })
    };

    tableCtrl.initRecord = null;
    tableCtrl.initTemplate = "";
    tableCtrl.getInitTemplate = function () {
        this.initTemplate = $("#init-panel-body").html();
        $("#init-panel-body").html("");
    };
    tableCtrl.showInit = function (id) {
        var record = this.getById(id);
        this.initRecord = record;

        $("#init-panel-body").html("");
        for (var i = 0; i < record.dataSources.length; i++) {
            var typeClass = record.dataSources[i].type === "MYSQL" ? "bg-info" : "bg-warning";
            var html = this.initTemplate
                .replace(new RegExp("{{index}}", "gm"), (i + 1))
                .replace(new RegExp("{{id}}", "gm"), record.dataSources[i].id)
                .replace(new RegExp("{{name}}", "gm"), record.dataSources[i].name)
                .replace(new RegExp("{{url}}", "gm"), record.dataSources[i].url)
                .replace(new RegExp("{{typeClass}}", "gm"), typeClass)
                .replace(new RegExp("{{typeValue}}", "gm"), record.dataSources[i].typeValue);
            $("#init-panel-body").append(html);

            var url = Url.dataService.dataAgentSearchByType + "?type=" + encodeURIComponent(record.dataSources[i].type)
            new Select2Ctrl("#init-panel-select-" + (i + 1), url, "id", "name", "select2").init();
        }

        $("#init-panel").removeClass("hide");
    };
    tableCtrl.hideInit = function () {
        this.initRecord = null;
        $("#init-panel").addClass("hide");
    };
    tableCtrl.checkInitRequire = function () {
        var valid = true;
        $("#init-panel select.select2").each(function (i, n) {
            if ($(n).attr("required") === "required" && Utils.isEmpty($(n).val())) {
                valid = false;
                $(n).attr("data-dropdown-css-class", "select2-danger")
                    .parent().removeClass("select2-info").addClass("select2-danger");
            } else {
                $(n).attr("data-dropdown-css-class", "select2-info")
                    .parent().removeClass("select2-danger").addClass("select2-info");
            }
        });
        $("#init-panel input:file").each(function (i, n) {
            if ($(n).attr("required") === "required" && $(n).prop("files").length === 0) {
                valid = false;
                $(n).removeClass("is-valid").addClass("is-invalid");
            } else {
                $(n).removeClass("is-invalid").addClass("is-valid");
            }
        });
        return valid;
    };
    tableCtrl.doInit = function () {
        var self = this;

        if (!self.checkInitRequire()) {
            return;
        }

        var initFiles = [];

        var executeInit = function () {
            var initParam = {details: initFiles};
            $.ajax({
                url: Url.dataService.dataProjectInit.replace("{id}", self.initRecord.id),
                type: HttpMethod.patch,
                contentType: ContentType.json,
                data: JSON.stringify(initParam),
                success: function (result, status, xhr) {
                    self.refreshById(self.initRecord.id);
                    self.hideInit();
                    parent.window.frameCtrl.toastr.success("初始化任务已经下发！");
                }
            });
        };

        var executeUpload = function () {
            $("#init-panel-body input:file").each(function (i, n) {
                var dataSourceId = $(n).attr("data-id");
                var index = $(n).attr("data-index");
                var files = $(n).prop("files");

                var $progress = $("#init-panel-progress-" + index);
                var $agent = $("#init-panel-select-" + index);
                if (files.length > 0) {
                    var formdata = new FormData();
                    formdata.append("multipartFile", files[0]);

                    var xhr = new XMLHttpRequest();
                    xhr.upload.onerror = function (ev) {
                        parent.window.frameCtrl.toastr.error("[" + xhr.status + "] " + xhr.responseJSON.error + ": " + xhr.responseJSON.message);
                        $progress.removeClass("bg-info").addClass("bg-danger")
                    };
                    xhr.upload.onprogress = function (ev) {
                        var per = Math.round(ev.loaded / ev.total * 100);
                        $progress.css("width", per + "%");
                    };
                    xhr.upload.onloadstart = function (ev) {
                        $progress.removeClass("bg-warning").removeClass("bg-danger").removeClass("bg-success")
                            .addClass("bg-info").css("width", "0%").parent().removeClass("bg-white");
                    };
                    xhr.upload.onload = function (ev) {
                        $progress.removeClass("bg-info").addClass("bg-success").css("width", "100%");
                    };
                    xhr.upload.onloadend = function (ev) {

                    };
                    xhr.onreadystatechange = function (ev) {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                                var dataAgentId = $agent.val();
                                initFiles.push({dataSourceId: dataSourceId, dataAgentId: dataAgentId, initFileId: xhr.responseText});
                                if (initFiles.length === self.initRecord.dataSources.length) {
                                    executeInit();
                                }
                            } else {
                                parent.window.frameCtrl.toastr.error("[" + xhr.status + "] " + xhr.responseJSON.error + ": " + xhr.responseJSON.message);
                            }
                        }
                    };
                    xhr.open(HttpMethod.post, Url.fileCreate, true);
                    xhr.send(formdata);
                }
            });
        };

        executeUpload();
    };
    tableCtrl.bindInitEvent = function () {
        var self = this;
        // 绑定更多按钮
        $("#table").on("click", ".init", function () {
            var id = $(this).attr("data-id");
            self.showInit(id);
        });
        // 绑定时间线按钮
        $("#table").on("click", ".line", function () {
            var id = $(this).attr("data-id");
            var record = self.getById(id);
            var uuid = Math.random().toString(36).slice(-8);
            var name = record.name + " 的 " + "时间线";
            var url = "cloud/html/data-project-time-line.html?id=" + id;
            parent.window.frameCtrl.windowCtrl.open(uuid, name, url);
        });
        $("#init-cancel").bind("click", function () {
            self.hideInit();
        });
        $("#init-ok").bind("click", function () {
            self.doInit();
        });
    };

    tableCtrl.upgradeRecord = null;
    tableCtrl.upgradeTemplate = "";
    tableCtrl.upgradeArea = {};
    tableCtrl.getUpgradeTemplate = function () {
        this.upgradeTemplate = $("#upgrade-panel-body").html();
        $("#upgrade-panel-body").html("");
    };
    tableCtrl.showUpgrade = function (id) {
        var self = this;
        var record = this.getById(id);
        this.upgradeRecord = record;

        $("#upgrade-panel-body").html("");
        for (var i = 0; i < record.dataSources.length; i++) {
            var typeClass = record.dataSources[i].type === "MYSQL" ? "bg-info" : "bg-warning";
            var html = this.upgradeTemplate
                .replace(new RegExp("{{index}}", "gm"), (i + 1))
                .replace(new RegExp("{{id}}", "gm"), record.dataSources[i].id)
                .replace(new RegExp("{{name}}", "gm"), record.dataSources[i].name)
                .replace(new RegExp("{{url}}", "gm"), record.dataSources[i].url)
                .replace(new RegExp("{{typeClass}}", "gm"), typeClass)
                .replace(new RegExp("{{typeValue}}", "gm"), record.dataSources[i].typeValue);
            $("#upgrade-panel-body").append(html);

            var url = Url.dataService.dataAgentSearchByType + "?type=" + encodeURIComponent(record.dataSources[i].type)
            new Select2Ctrl("#upgrade-panel-select-" + (i + 1), url, "id", "name", "select2").init();

            var area = CodeMirror.fromTextArea(document.getElementById("upgrade-panel-input-" + (i + 1)), {
                mode: "text/x-sql",
                theme: "darcula"
            });
            self.upgradeArea[record.dataSources[i].id] = area;
        }
        $("#upgrade-panel-id").val(id);

        $("#upgrade-panel").removeClass("hide");
    };
    tableCtrl.hideUpgrade = function () {
        this.upgradeRecord = null;
        $("#upgrade-panel").addClass("hide");
    };
    tableCtrl.checkUpgradeRequire = function () {
        var param = {};
        param.name = $("#upgrade-panel-name").val();
        param.recordOnly = $("#upgrade-record-only").prop("checked");
        param.details = [];
        for (var i = 0; i < this.upgradeRecord.dataSources.length; i++) {
            var dataSourceId = this.upgradeRecord.dataSources[i].id;
            var dataAgentId = $("#upgrade-panel-select-" + (i + 1)).val();
            var sql = this.upgradeArea[dataSourceId].getValue();
            param.details.push({dataSourceId: dataSourceId, dataAgentId: dataAgentId, sql: sql});
        }

        if (Utils.isEmpty(param.name)) {
            parent.window.frameCtrl.toastr.error("请填写说明");
            return undefined;
        }

        for (var i = 0; i < param.details.length; i++) {
            if (Utils.isEmpty(param.details[i].sql)) {
                parent.window.frameCtrl.toastr.error("请填写脚本");
                return undefined;
            }
            if (Utils.isEmpty(param.details[i].dataAgentId)) {
                parent.window.frameCtrl.toastr.error("请选择代理终端");
                return undefined;
            }
        }
        
        return param;
    };
    tableCtrl.doUpgrade = function () {
        var self = this;

        var param = self.checkUpgradeRequire();
        if (Utils.isEmpty(param)) {
            return;
        }

        $.ajax({
            url: Url.dataService.dataProjectUpgrade.replace("{id}", self.upgradeRecord.id),
            type: HttpMethod.patch,
            contentType: ContentType.json,
            data: JSON.stringify(param),
            success: function (result, status, xhr) {
                self.refreshById(self.upgradeRecord.id);
                self.hideUpgrade();
                if (param.recordOnly === true) {
                    parent.window.frameCtrl.toastr.success("记录成功！");
                } else {
                    parent.window.frameCtrl.toastr.success("升级任务已经下发！");
                }

            }
        });
    };
    tableCtrl.bindUpgradeEvent = function () {
        var self = this;
        // 绑定更多按钮
        $("#table").on("click", ".upgrade", function () {
            var id = $(this).attr("data-id");
            self.showUpgrade(id);
        });
        $("#upgrade-cancel").bind("click", function () {
            self.hideUpgrade();
        });
        $("#upgrade-ok").bind("click", function () {
            self.doUpgrade();
        });
    };

    tableCtrl.getTemplate();
    tableCtrl.getRecords();
    tableCtrl.bindEvent();
    tableCtrl.bindOtherEvent();

    tableCtrl.getMoreTemplate();
    tableCtrl.bindMoreEvent();

    tableCtrl.getInitTemplate();
    tableCtrl.bindInitEvent();

    tableCtrl.getUpgradeTemplate();
    tableCtrl.bindUpgradeEvent();

    var listener = function (event) {
        if (event.type === "DATA_PROJECT_UPGRADE_RUNNING" ||
            event.type === "DATA_PROJECT_UPGRADE_SUCCESS" ||
            event.type === "DATA_PROJECT_UPGRADE_ERROR"
        ) {
            tableCtrl.refreshById(event.data);
        }
    };
    listener.owner = window.location.href;
    parent.window.frameCtrl.websockerCtrl.eventListener.push(listener);
</script>

</body>
</html>